package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.AttachmentManager;
import com.xyzh05.model.Attachment;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class AttachmentAction extends BaseAction implements Preparable {
    private AttachmentManager attachmentManager;
    private List attachments;
    private Attachment attachment;
    private Long id;
    private String query;

    public void setAttachmentManager(AttachmentManager attachmentManager) {
        this.attachmentManager = attachmentManager;
    }

    public List getAttachments() {
        return attachments;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String attachmentId = getRequest().getParameter("attachment.id");
            if (attachmentId != null && !attachmentId.equals("")) {
                attachment = attachmentManager.get(new Long(attachmentId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        attachments = attachmentManager.search(query, Attachment.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Attachment getAttachment() {
        return attachment;
    }

    public void setAttachment(Attachment attachment) {
        this.attachment = attachment;
    }

    public String delete() {
        attachmentManager.remove(attachment.getId());
        saveMessage(getText("attachment.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            attachment = attachmentManager.get(id);
        } else {
            attachment = new Attachment();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (attachment.getId() == null);

        attachmentManager.save(attachment);

        String key = (isNew) ? "attachment.added" : "attachment.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}